<template>
  <el-dialog :title="`${form.patProFileId ? '修改' : '添加'}平面图`" :visible.sync="show" :close-on-click-modal="false" append-to-body :show-close="!btnLoading" width="500px" @closed="closed">
    <div class="loading" v-loading="uploading" element-loading-text="图片上传处理中" element-loading-background="rgba(255, 255, 255, 0.5)" v-if="uploading" />
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="90px">
      <el-form-item prop="projectId" class="hide" />
      <el-form-item prop="patProFileId" class="hide" />
      <el-form-item label="平面图类型" prop="fileType">
        <el-select v-model="form.fileType" placeholder="请选择平面图类型" filterable style="width: 100%">
          <el-option v-for="dict in dict.type.cq_patrol_file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="平面图名称" prop="fileName"><el-input v-model.trim="form.fileName" placeholder="请输入平面图名称" :maxlength="100" /></el-form-item>
      <el-form-item label="上传平面图" prop="fileId">
        <el-upload
          ref="upload"
          class="uploader"
          :action="FILE_MULTI_UPLOAD_URL"
          :data="{ type: 'cqPatrolProFile' }"
          name="files"
          accept=".png,.jpg,.jpeg"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-error="onUploadError"
          :on-success="onUploadSuccess"
        >
          <el-image class="img g-img-placeholder" :src="imgUrl" fit="cover" v-if="imgUrl" />
          <i v-else class="el-icon-plus uploader-icon" />
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 添加或修改平面图
import { editFormMixin } from '@/utils/mixin'
import { FILE_MULTI_UPLOAD_URL, getFileURL } from '@/api/common'
import { addPatProFile, setPatProFile } from '@/api/cq/patrol'
const acceptTypeList = ['image/jpeg', 'image/png', 'image/jpg']
export default {
  mixins: [editFormMixin],
  dicts: ['cq_patrol_file_type'],
  data() {
    return {
      FILE_MULTI_UPLOAD_URL,
      primaryKey: 'patProFileId',
      addApi: addPatProFile,
      updateApi: setPatProFile,
      form: {
        projectId: '',
        patProFileId: '',
        fileType: '',
        fileName: '',
        fileId: ''
      },
      rules: {
        fileType: [{ required: true, message: '请选择平面图类型' }],
        fileName: [{ required: true, message: '请输入平面图名称' }],
        fileId: [{ required: true, message: '请上传平面图' }]
      },
      uploading: false
    }
  },
  computed: {
    imgUrl() {
      const { fileId } = this.form
      if (!fileId) return ''
      return getFileURL(fileId)
    }
  },
  methods: {
    closed() {
      // TODO 上传了图片没提交，则移除
      // if (this.form.fileId && !this.form.patProFileId) this.deleteFile(this.form.fileId)

      this.$refs.form.resetFields()
    },
    beforeUpload(file) {
      const isAccept = acceptTypeList.includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isAccept) this.msgError('上传图片只能是 JPG/PNG 格式!')
      if (!isLt10M) this.msgError('上传图片大小不能超过 10MB!')

      const isOk = isAccept && isLt10M
      if (!this.uploading) this.uploading = isOk
      return isOk
    },
    onUploadError(err) {
      this.uploading = false
      this.msgError(`上传失败 ${err?.msg || ''}`)
    },
    async onUploadSuccess(res) {
      this.uploading = false
      if (res.code !== 200) return this.msgError(`上传失败 ${res.msg || ''}`)

      const oldFileId = this.form.fileId
      this.form.fileId = res.data[0]
      if (oldFileId) this.deleteFile(oldFileId)
    },
    async deleteFile(fileId) {
      // TODO 删除旧图
      // const res = await deleteFile(fileId).catch(() => false)
      // if (res === false) return
    }
  }
}
</script>
<style lang="scss" scoped>
.loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
}
.uploader {
  /deep/ .el-upload {
    position: relative;
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    &:hover {
      border-color: #409eff;
    }
  }
  .img {
    width: 100%;
    height: 100%;
  }
  .uploader-icon {
    font-size: 28px;
    color: #8c939d;
    line-height: 150px;
    text-align: center;
  }
}
</style>
